<?php

namespace app\admin\model;

use think\Model;
use app\admin\model\share\ShareUser;


class UserWithdraw extends Model
{





    // 表名
    protected $table = 'user_withdraw';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'payType_text',
        'payTime_text',
        'auditStatus_text',
        'auditTime_text'
    ];


    const TYPE_0 = '0';
    public function getTypeList()
    {
        return ['0' => __('Type 0')];
    }

    // 获取订单号
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = 'tx'.date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }
    const PAY_TYPE_0 = '0';// 0=未支付
    const PAY_TYPE_1 = '1';// 1=支付中
    const PAY_TYPE_2 = '2';// 2=支付成功
    const PAY_TYPE_3 = '3';// 3=支付失败

    const WITH_TYPE_0 = '0'; //新余额,
    const WITH_TYPE_1 = '1';//1=老余额
    const WITH_TYPE_2 = '2';//,2=广告余额
    public function getPaytypeList()
    {
        return ['0' => __('Paytype 0'), '1' => __('Paytype 1'), '2' => __('Paytype 2'), '3' => __('Paytype 3')];
    }
    public function getWithdrawStatusList()
    {
        return ['0' => __('Paytype 0'), '1' => __('Paytype 1'), '2' => __('Paytype 2'), '3' => __('Paytype 3')];
    }

    const Auditstatus_0 = '0'; //未审核,
    const Auditstatus_1 = '1';//1=审核通过
    const Auditstatus_2 = '2';//,2=审核驳回
    public function getAuditstatusList()
    {
        return ['0' => __('Auditstatus 0'), '1' => __('Auditstatus 1'), '2' => __('Auditstatus 2')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payType']) ? $data['payType'] : '');
        $list = $this->getPaytypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['payTime']) ? $data['payTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getAuditstatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['auditStatus']) ? $data['auditStatus'] : '');
        $list = $this->getAuditstatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAudittimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['auditTime']) ? $data['auditTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setAudittimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function addWithdraw($option)
    {
        return $this->insertGetId($option);
    }
    public function timer()
    {
        // $config = config('thirdpay.linghuo');
        // $with_type = $config['with_type'];
        // $linghuo = new \linghuo\v2\Linghuo;

        $configs = config('thirdpay.linghuos');
        static $linghuos = [];
        foreach ($configs as $ckey => $cvalue) {
            $with_type = $cvalue['with_type'];
            if (!empty($linghuos[$with_type]) ) {
                $linghuo = $linghuos[$with_type];
            }else{
                $linghuo = new \linghuo\v2\Linghuo($cvalue);
                $linghuos[$with_type] = $linghuo;
            }

            // 更新提现审核
            \think\Db::transaction(function() use ($linghuo,$with_type){

                // $where['with_type'] = ['in',[$this->model::WITH_TYPE_0,$this->model::WITH_TYPE_1]];

                $userWithdraw = UserWithdraw::where('payType','=',UserWithdraw::PAY_TYPE_0) //未支付的
                    ->where('auditStatus','=',UserWithdraw::Auditstatus_1) // 审核通过的
                    ->where('with_type','=',$with_type) // 提现类型
                    // ->where('with_type','in',[UserWithdraw::WITH_TYPE_0,UserWithdraw::WITH_TYPE_1]) // 不是广告提现
                    ->lock(true)
                    ->limit(3)
                    ->select();

                foreach ($userWithdraw as $key=> $value) {
                    $value->payType = UserWithdraw::PAY_TYPE_1;//支付中
                    $value->save();
                }

                // var_dump($userWithdraw);exit;
                $userMsg = '当前用户已注销';
                if (!empty($userWithdraw)) {
                    // memberId    是   string(36)  会员ID
                    // name    是   string(50)  会员名称
                    // idCard  是   string(50)  身份证号
                    // fee 是   string(20)  金额 单位元，精确到两位小数点 示例： 10.05元

                    foreach ($userWithdraw as $key=> $value) {
                        $shareUserOne = ShareUser::where('user_id','=',$value->user_id)->find();
                        // 注销直接失败
                        if (!$shareUserOne) {
                            $value->payMsg = $userMsg;
                            $value->payType = UserWithdraw::PAY_TYPE_3;
                            $value->save();
                            unset($userWithdraw[$key]);
                            continue;
                        }
                        $payList = [];
                        $payList[] = [
                            'systemId'=>$value['systemId'],
                            'name'=>$value['memberName'],
                            'idCard'=>strtoupper($value['idCard']),
                            'fee'=> sprintf('%.2f',$value['money']*0.97),
                        ];
                        $value->pay_merchantNo = $linghuo->merchantNo;//灵活商户号
                        $value->pay_productCode = $linghuo->productCode;//灵活产品编号
                        $value->pay_taskCode = $linghuo->taskCode;//灵活任务编号

                        $res = $linghuo->pay($payList);
                        // var_dump($res);
                        $payType = UserWithdraw::PAY_TYPE_1;//支付中
                        $members = [];
                        $failMembers = [];
                        if (
                            $res['code'] !== 1
                            && !empty($res['data'])
                            && (
                                (!empty($res['data']['code']) && $res['data']['code'] != 200 )
                                || ( !empty($res['data']['result']) && $res['data']['result']['statusCode'] == '1002' )
                            )
                        ) {
                            // 失败返回
                            $payType = UserWithdraw::PAY_TYPE_3;//支付失败
                            if (!empty($res['data']['result']['failList'])) {
                                foreach ($res['data']['result']['failList'] as  $mvalue) {
                                    // var_dump( $value);exit;
                                    $failMembers[$mvalue['systemId']] = $mvalue;
                                }
                            }

                        }else{
                            foreach ($res['data']['result']['payList'] as  $mvalue) {
                                // var_dump( $value);exit;
                                $members[$mvalue['systemId']] = $mvalue;
                            }
                        }

                        if (!empty($members[$value['systemId']])) {
                            $value->orderNo = $members[$value['systemId']]['orderNo'];//交易流水号
                        }
                        $value->payType = $payType;//支付中

                        if ($shareUserOne && $payType == UserWithdraw::PAY_TYPE_3) {
                            $msg = '-';
                            // 失败返还余额
                            if ($shareUserOne->lock_money < $value['money']) {
                                 $msg .= '系统异常：锁定余额'.$shareUserOne->lock_money.'小于提现余额'.$value['money'];
                            // }else{
                            //     $shareUserOne->unlock_money($shareUserOne,$value['money'],ShareUser::UNLOCK_MONEY_TRUE,0, $value['with_type']);
                            }
                            $value->payMsg =  $res['msg'].( !empty($failMembers[$value['systemId']])? ('：'.$failMembers[$value['systemId']]['remark']):'' ) . $msg;
                        }
                        $value->save();
                        // $value->payType = UserWithdraw::PAY_TYPE_1;//支付中
                        // $value->save();
                    }
                }

            });
            //更新提现支付中
            //1分钟5次
            //2分钟10次
            //5分钟 20次
            //10分钟 30次
            //30分钟 40次

            \think\Db::transaction(function() use ($linghuo,$with_type){
                // $userWithdraw = UserWithdraw::where('payType','in',[UserWithdraw::PAY_TYPE_1,UserWithdraw::PAY_TYPE_3]) //支付中
                $userWithdraw = UserWithdraw::where('payType','=',UserWithdraw::PAY_TYPE_1) //支付中
                    ->where('auditStatus','=',UserWithdraw::Auditstatus_1) // 审核通过的
                    ->where('orderNo','<>','') // 审核通过的
                    ->where('with_type','=',$with_type) // 提现类型
                    // ->where('with_type','in',[UserWithdraw::WITH_TYPE_0,UserWithdraw::WITH_TYPE_1]) // 不是广告提现
                // $userWithdraw = UserWithdraw::where('id','=',13) // 审核通过的
                    // ->fetchSql(true)
                    ->where(function($query)
                    {
                        $query->where('pay_qnum','=',0)
                        ->whereOr(function($query1)
                            {
                                $where = [
                                    'pay_qnum'=>['<',5],
                                    'auditTime'=>['<=',time()-60],
                                ];
                                $query1->where($where);
                            })
                        ->whereOr(function($query1)
                            {
                                $where = [
                                    'pay_qnum'=>['<',10],
                                    'auditTime'=>['<=',time()-120],
                                ];
                                $query1->where($where);
                            })
                        ->whereOr(function($query1)
                            {
                                $where = [
                                    'pay_qnum'=>['<',20],
                                    'auditTime'=>['<=',time()-300],
                                ];
                                $query1->where($where);
                        })
                        ->whereOr(function($query1)
                            {
                                $where = [
                                    'pay_qnum'=>['<',30],
                                    'auditTime'=>['<=',time()-600],
                                ];
                                $query1->where($where);
                        })->whereOr(function($query1)
                            {
                                $where = [
                                    'pay_qnum'=>['<',40],
                                    'auditTime'=>['<=',time()-1800],
                                ];
                                $query1->where($where);
                            });
                    })
                    ->lock()
                    // ->fetchSql(true)
                    ->select();
                // var_dump($userWithdraw);exit;
                // exit;
                $userMsg = '当前用户已注销';
                foreach ($userWithdraw as $key => $value) {
                    $res = $linghuo->detail($value['orderNo']);
                    $value->pay_qnum++;
                    $value->save();
                    // var_dump($res);
                    if (
                        $res['code'] !== 1 // 失败返回
                        || !in_array($res['data']['result']['payStatus'],[$linghuo::detail_payStatus_2,$linghuo::detail_payStatus_3,$linghuo::detail_payStatus_4]) // 不是 成功、失败、撤回
                    ) {
                        \think\Log::record('error：' . var_export($res,true), 'pay_withdraw');
                        continue;
                    }
                    $value->payType =  $value::PAY_TYPE_3;
                    $lock = ShareUser::UNLOCK_MONEY_TRUE;//余额是否要加回
                    $shareUserOne = ShareUser::where('user_id','=',$value->user_id)->find();
                    if ($res['data']['result']['payStatus'] == $linghuo::detail_payStatus_2) {
                        $lock = ShareUser::UNLOCK_MONEY_FALSE;
                        $value->payType =  $value::PAY_TYPE_2;
                        $value->pay_money =  $res['data']['result']['fee'];
                        $value->payTime =  strtotime($res['data']['result']['payTime']);
                    }
                    $value->payMsg =  $res['data']['result']['remark'];
                    if (!$shareUserOne) {
                        $value->payMsg .= $userMsg;
                    }
                    // var_dump($value->payType);exit;
                    // 修改只有成功才处理余额
                    if ($shareUserOne) {
                        $msg = '-';
                        // 失败返还余额
                        if ($shareUserOne->lock_money < $value['money']) {
                             $value->payMsg .= '-系统异常：锁定余额'.$shareUserOne->lock_money.'小于提现余额'.$value['money'];
                        }else{
                            $shareUserOne->unlock_money($shareUserOne,$value['money'],$lock, 0,$value['with_type']);
                        }
                    }
                    $value->save();
                }
            });
        }
    }
}
